package com.frame.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.frame.common.core.entity.SysRole;
import com.frame.common.core.entity.SysUser;
import com.frame.common.core.security.utils.SecurityUtils;
import com.frame.db.util.Condition;
import com.frame.db.util.Query;
import com.frame.security.service.ISysRoleService;
import com.frame.security.service.ISysUserService;
import com.frame.stant.constans.UserConstants;
import com.frame.stant.utils.R;
import com.frame.system.service.ISysPostService;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@Api(tags = "用户")
@RestController
@RequestMapping("/system/user")
@AllArgsConstructor
public class SysUserController  {

    private final ISysUserService userService;
    private final ISysRoleService roleService;
    private final ISysPostService postService;


    /**
     * 获取用户列表
     */
    @PreAuthorize("@custom.hasAnyAuthority('system:user:list')")
    @GetMapping("/list")
    public R list(SysUser user, Query query) {
        IPage<SysUser> list = userService.selectUserList(Condition.page(query),user);
        return R.success(list);
    }

//    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
//    @PreAuthorize("@custom.hasAnyAuthority('system:user:export')")
//    @GetMapping("/export")
//    public R export(SysUser user) {
//        List<SysUser> list = userService.selectUserList(user);
//        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
//        return util.exportExcel(list, "用户数据");
//    }

//    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
//    @PreAuthorize("@custom.hasAnyAuthority('system:user:import')")
//    @PostMapping("/importData")
//    public R importData(MultipartFile file, boolean updateSupport) throws Exception {
//        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
//        List<SysUser> userList = util.importExcel(file.getInputStream());
//        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
//        String operName = loginUser.getUsername();
//        String message = userService.importUser(userList, updateSupport, operName);
//        return R.success(message);
//    }

//    @GetMapping("/importTemplate")
//    public R importTemplate() {
//        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
//        return util.importTemplateExcel("用户数据");
//    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@custom.hasAnyAuthority('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public R getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        R result = R.success();
        List<SysRole> roles = roleService.selectRoleAll();
        Map map = Maps.newHashMap();
        map.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        map.put("posts", postService.list());
        if (null != userId) {
            map.put("userInfo", userService.selectUserById(userId));
            map.put("postIds", postService.selectPostListByUserId(userId));
            map.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        result.setData(map);
        return result;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@custom.hasAnyAuthority('system:user:add')")
//    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@Validated @RequestBody SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            return R.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
//        else if (StringUtils.isNotEmpty(user.getPhoneNumber()) && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
//            return R.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
//        } else if (StringUtils.isNotEmpty(user.getEmail()) && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
//            return R.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
//        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return R.success(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@custom.hasAnyAuthority('system:user:edit')")
//    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
//        if (StringUtils.isNotEmpty(user.getPhoneNumber()) && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
//            return R.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
//        } else if (StringUtils.isNotEmpty(user.getEmail()) && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
//            return R.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
//        }
        user.setUpdateBy(SecurityUtils.getUsername());
        return R.success(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@custom.hasAnyAuthority('system:user:remove')")
//    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public R remove(@PathVariable List<Long> userIds) {
        return R.success(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@custom.hasAnyAuthority('system:user:resetPwd')")
//    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public R resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return R.success(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@custom.hasAnyAuthority('system:user:edit')")
//    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public R changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        return R.success(userService.updateUserStatus(user));
    }
}
